import 
{ 
    ref,
    reactive,
    getCurrentInstance, 
    toRefs,
    onMounted,
    onUnmounted
} from 'vue'
import { useRouter } from 'vue-router'
import { ElIcon,ElAvatar,ElLoading } from 'element-plus'
import { ElMessage } from 'element-plus'

export default {
    name:'loginPage',
    components:{ ElIcon,ElAvatar,ElLoading },
    setup() {
        let loginForm = reactive({
            username:'',
            password:''
        })
        const loading = ref(false)
        const { proxy } = getCurrentInstance();//获取上下文
        const router = useRouter()
        
        function login(){
            for(let key in loginForm){
                if(loginForm[key].trim()===''){
                    ElMessage({
                        message: '信息不能为空',
                        type: 'warning',
                    })
                    return;
                }
            }
            if(loading.value){
                return;
            }
            loading.value=true
            setTimeout(async() => {
                //调用登录api函数(废除)
                // const data = await proxy.$http.login(proxy,loginForm.username,loginForm.password)
                // //保存信息到本地
                // proxy.$utils.cache.token.set(proxy.$utils.secret.Encrypt(data.objectId))
                // proxy.$utils.cache.username.set(data.username)
                // let code = proxy.$utils.secret.md5encode('os'+data.objectId+data.username)
                // proxy.$utils.cache.id.set(code)
                // proxy.$utils.cache.bmob.remove()
                if (loginForm.username === 'admin' && loginForm.password === '123456')
                {
                    const data = {
                        objectId:'os123456',
                        username:'user-123'
                    }
                    proxy.$utils.cache.token.set(proxy.$utils.secret.Encrypt(data.objectId))
                    proxy.$utils.cache.username.set(data.username)
                    let code = proxy.$utils.secret.md5encode('os'+data.objectId+data.username)
                    proxy.$utils.cache.id.set(code)
                    router.replace('mainPage')
                }
                else
                {
                    ElMessage({
                        message: '账号密码不正确',
                        type: 'error',
                    })
                }
            }, 500);
            
        }
        function enter(e){
            if(e.keyCode===13){
                login()
            }
        }

        onMounted(()=>{
            //增加回车事件
            window.addEventListener("keydown", enter)
        })
        onUnmounted(()=>{
            window.removeEventListener("keydown", enter)
        })
        return {
            ...toRefs(loginForm),
            loading,
            login
        }
    }
}